package com.enliteapp.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

@WebService(name="AccessWeaverService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class AccessWeaverService {

	@WebMethod
	public String getApplications(InputStream is)
			throws ParserConfigurationException, SAXException, IOException {

//		XStream xstream = new XStream(new DomDriver());
//		xstream.alias("applications", Applications.class);
//		xstream.alias("application", Application.class);
//		xstream.addImplicitCollection(Applications.class, "apps");

		String filePath	=	"C:\\aw-files\\Applications.txt";
		return readFileAsString(filePath);
	
//		System.out.println("File contents >>>>>"+fileAsString);
//		Applications app = (Applications) xstream.fromXML(is);

//		return xstream.toXML(app);
	}

	@WebMethod
	public String getTempatesForApplication(InputStream is, String appId) throws IOException {

		String filePath	=	"C:\\aw-files\\Templates.txt";
		return readFileAsString(filePath);
	}
//	@WebMethod
//	public String getTempatesForApplication(InputStream is, String appId) {
//
//		System.out.println(">>>>>>>>>>>>>>."+appId);
//		Templates refinedTemplates 	= new Templates();
//		XStream xstream = new XStream(new DomDriver());
//		xstream.alias("source", Templates.class);
//		xstream.alias("template", Template.class);
//		xstream.addImplicitCollection(Templates.class, "templates");
//
//		Templates templates = (Templates) xstream.fromXML(is);
//		
//		List<Template> temps = templates.getTemplates();
//		for (Iterator iterator = temps.iterator(); iterator.hasNext();) {
//			Template template = (Template) iterator.next();
//			if(template.getApp_id().equals(appId)) {
//				refinedTemplates.addTemplate(template);
//			}
//			
//		}
//
//		System.out.println(refinedTemplates.getTemplates().size());
//		return xstream.toXML(refinedTemplates);
//	}
	
    private static String readFileAsString(String filePath)
    throws java.io.IOException{
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }
}
